package gdt.service.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;


@SuppressWarnings("unchecked")
public class Validator {

	private Map validatorCache = new HashMap();

	public boolean validate(Object value, MessageContext context) {
		Class type = value.getClass();
		ClassValidator validator = (ClassValidator)validatorCache.get(type);
		if (validator == null) {
			validator = new ClassValidator(type,ResourceBundle.getBundle(messageSource));
			validatorCache.put(type, validator);
	    }
		InvalidValue[] invalidValues = validator.getInvalidValues(value);
		translateToSpringValidationErrors(invalidValues, context);
		if(invalidValues.length > 0)
			return false;
		else
			return true;
	}

	private void translateToSpringValidationErrors(InvalidValue[] invalidValues, MessageContext context) {
		for (InvalidValue invalidValue : invalidValues) {
			String propertyName = invalidValue.getPropertyName();
			if (propertyName == null) {
				context.addMessage((new MessageBuilder()).error().defaultText(invalidValue.getMessage()).build());
			}else{
				context.addMessage((new MessageBuilder()).error().defaultText(invalidValue.getMessage()).resolvableArg(propertyName).build());
			}
	    }
	}

	
	private String messageSource;
	
	public String getMessageSource() {
		return messageSource;
	}

	public void setMessageSource(String messageSource) {
		this.messageSource = messageSource;
	}
	
}
